package com.situ.mall.job;

import com.situ.mall.api.admin.AdminClient;
import com.situ.mall.api.product.ProductClient;
import com.situ.mall.controller.UploadController;
import com.situ.mall.util.AliOSSUtil;
import com.situ.mall.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.CollectionUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Configuration
public class DeleteImageJob {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ProductClient productClient;
    @Autowired
    private AdminClient adminClient;

    @Scheduled(cron = "0 */1 * * * *")
    public void deleteImage() {
        System.out.println("DeleteImageJob.deleteImage");
        //1。查询所有微服务中使用的图片
        Result<Set<String>> productResult = productClient.selectAllImage();
        Result<Set<String>> adminResult = adminClient.selectAllImage();
        Set<String> set = new HashSet<>();
        if (productResult.getCode() == 0) {
            set.addAll(productResult.getData());
        }
        if (adminResult.getCode() == 0) {
            set.addAll(adminResult.getData());
        }
        //2.放到Redis中set集合中
        redisTemplate.opsForSet().add(UploadController.UPLOAD_IMAGE_TO_DB, set.toArray(new String[0]));
        //3.计算两个Set集合差集
        Set<String> diffSet = redisTemplate.opsForSet().difference(UploadController.UPLOAD_IMAGE, UploadController.UPLOAD_IMAGE_TO_DB);
        if (!CollectionUtils.isEmpty(diffSet)) {
            for (String imageName : diffSet) {
                //删除阿里云中垃圾图片
                AliOSSUtil.deleteFile(imageName);
                System.out.println("删除图片：" + imageName);
            }
            //删除redis中两个set集合
            redisTemplate.delete(UploadController.UPLOAD_IMAGE_TO_DB);
            redisTemplate.delete(UploadController.UPLOAD_IMAGE);
        }
    }
}
